package com.cqan.account.entity;

import java.util.List;

import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.JoinColumn;
import javax.persistence.JoinTable;
import javax.persistence.ManyToMany;
import javax.persistence.ManyToOne;
import javax.persistence.OneToMany;
import javax.persistence.OrderBy;
import javax.persistence.Table;

import org.hibernate.annotations.Cache;
import org.hibernate.annotations.CacheConcurrencyStrategy;
import org.hibernate.annotations.Fetch;
import org.hibernate.annotations.FetchMode;

import com.cqan.entity.pk.IdEntity;


@Entity
//表名与类名不相同时重新定义表名.
@SuppressWarnings("serial")
@Table(name = "DMS_DEPARTMENT")
//默认的缓存策略.
@Cache(usage = CacheConcurrencyStrategy.READ_WRITE)
public class Department extends IdEntity {

	private List<Department> children;

	private boolean enabled;

	private String name;

	private Department parent;

	private List<Role> roles;

	private List<User> users;

	@OneToMany(mappedBy = "parent", cascade = { CascadeType.REFRESH }, fetch = FetchType.LAZY, targetEntity = Department.class)
	@Cache(usage = CacheConcurrencyStrategy.READ_WRITE)
	public List<Department> getChildren() {
		return children;
	}

	@Column(name = "NAME")
	public String getName() {
		return name;
	}

	@ManyToOne
	@JoinColumn(name = "PID")
	public Department getParent() {
		return parent;
	}

	// 多对多定义
	@ManyToMany
	// 中间表定义,表名采用默认命名规则
	@JoinTable(name = "DMS_DEPARTMENT_ROLE", joinColumns = { @JoinColumn(name = "DID") }, inverseJoinColumns = { @JoinColumn(name = "RID") })
	// Fecth策略定义
	@Fetch(FetchMode.SUBSELECT)
	// 集合按id排序.
	@OrderBy("id")
	// 集合中对象id的缓存.
	@Cache(usage = CacheConcurrencyStrategy.READ_WRITE)
	public List<Role> getRoles() {
		return roles;
	}

	@ManyToMany(cascade = CascadeType.REFRESH, mappedBy = "departments", fetch = FetchType.LAZY)
	public List<User> getUsers() {
		return users;
	}

	@Column(name = "ENABLED")
	public boolean isEnabled() {
		return enabled;
	}

	public void setChildren(List<Department> children) {
		this.children = children;
	}

	public void setEnabled(boolean enabled) {
		this.enabled = enabled;
	}

	public void setName(String name) {
		this.name = name;
	}

	public void setParent(Department parent) {
		this.parent = parent;
	}

	public void setRoles(List<Role> roles) {
		this.roles = roles;
	}

	public void setUsers(List<User> users) {
		this.users = users;
	}

}
